Ext.ns('app.crud.reports');

app.crud.reports.canEdit = false;
app.crud.reports.canDelete = false;

Ext.define('app.FieldSet',{
	extend:'Ext.form.FieldSet',
	
	initComponent: function(){
		this.callParent(arguments);
		this.addEvents(
	            /**
	             * @event beforeexpand
	             * @param {app.FieldSet} component
	             */
				'beforeexpand',
				/**
	             * @event beforecollapse
	             * @param {app.FieldSet} component
	             */
				'beforecollapse'
		);  
	},
	setExpanded:function(expanded){	
		var me = this;
		if(expanded){
			this.fireEvent('beforeexpand');
		}else{
			this.fireEvent('beforecollapse');
		}
		return this.callParent(arguments);	
	}
});

Ext.define('app.crud.reports.JoinSelector',{
	extend:'Ext.panel.Panel',
	alias:'widget.joinselector',
	
	object:null,
	parentPart:null,
	parentField:null,
	value:null,
	autoHeight:true,
	deleteButton:null,

	initComponent:function(){
		this.layout = 'column';
		this.bodyPadding = 3;
		this.bodyCls = 'formBody';
		this.columns = 3;
		this.height = 28;
		
		this.dataCombo = Ext.create('Ext.form.field.ComboBox',{
      	  displayField:'title',
      	  valueField:'id',
      	  queryMode:'local',
      	  value:this.value,
      	  forceSelection:true,
      	  store:Ext.create('Ext.data.Store', {
      		  model:'app.comboModel',
      		  data:[
      		        {id:1, title:"Left"},
      		        {id:2 ,title:"Right"},
      		        {id:3 ,title:"Inner"}
      		  ]
      	  }),
      	  listeners:{
      		  change:{
      			  fn:this.joinSelected,
      			  scope:this
      		  }
      	  }
		});
				
		this.deleteButton = Ext.create('Ext.Button',{
			tooltip:appLang.REMOVE_JOIN,
			icon:'/i/system/delete.gif',
			handler:this.removePart,
			scope:this
		});
		
		this.tbar = [this.deleteButton , appLang.JOIN_TYPE, this.dataCombo];
		this.callParent(arguments);
		
		this.addEvents(
				/**
	             * @event objectAdded
	             */
				'partRemoved'
		);  
	},
	joinSelected:function(){
		var me = this;
		Ext.Ajax.request({
		 		url: app.root+ "setjoin",
		 		method: 'post',
		 		params:
		 		{
		 			object:me.object,
		 			parentpart:me.parentPart,
		 			parentfield:me.parentField,
		 			jointype:this.dataCombo.getValue()
		 		},
		        success: function(response, request) {
		 			response =  Ext.JSON.decode(response.responseText);
		 			if(response.success){
		 				//me.fireEvent('partRemoved');
		 			}else{
		 			    Ext.Msg.alert(appLang.MESSAGE,response.msg);   	
		 			}
		       },
		       failure:function() {
		       		Ext.Msg.alert(appLang.MESSAGE, appLang.MSG_LOST_CONNECTION);   
		       }
		 });
	},
	removePart:function(){
		var me = this;
		Ext.Ajax.request({
		 		url: app.root+ "deselectsub",
		 		method: 'post',
		 		params:
		 		{
		 			object:me.object,
		 			parentpart:me.parentPart,
		 			parentfield:me.parentField
		 		},
		        success: function(response, request) {
		 			response =  Ext.JSON.decode(response.responseText);
		 			if(response.success){
		 				me.fireEvent('partRemoved');
		 			}else{
		 			    Ext.Msg.alert(appLang.MESSAGE,response.msg);   	
		 			}
		       },
		       failure:function() {
		       		Ext.Msg.alert(appLang.MESSAGE, appLang.MSG_LOST_CONNECTION);   
		       }
		 });
	}
});

Ext.define('app.crud.reports.FieldRecord',{
	extend:'Ext.panel.Panel',
	alias:'widget.reportfield',
	
	itemsLoaded:false,
	
	valueSelected:false,
	valueTitle:null,
	valueAlias:null,
	valueIsLink:false,
	valueSelectSub:false,
	valueField:null,
	vauleObject:null,
	valueSubObject:null,
	valueSubObjectTtile:null,
	valuePartId:null,
	
	fieldPanel:null,
	childPanel:null,
	fieldSelected:null,
	fieldTitle:null,
	fieldAlias:null,
	fieldAddSub:null,
	
	initComponent:function(){
		
		this.bodyPadding = 5;
		//this.bodyCls = 'formBody';
		this.border = false;
		
		this.fieldSelected = Ext.create('Ext.form.field.Checkbox' , {
			inputValue:1,
			uncheckedValue:0,
			width:30,
			checked:this.valueSelected,
			listeners:{
				change:{
					fn:function( field,  newValue,  oldValue, eOpts ){
						this.saveField('select' , newValue);
					},
					scope:this,
					buffer:500
				}
			}
		});
		
		this.fieldTitle = Ext.create('Ext.form.field.Text',{
			value:this.valueTitle,
			listeners:{
				change:{
					fn:function( field,  newValue,  oldValue, eOpts ){
						this.saveField('title' , newValue);
					},
					scope:this,
					buffer:500
				}
			}
		});
		
		this.fieldAlias = Ext.create('Ext.form.field.Text',{
			value:this.valueAlias,
			listeners:{
				change:{
					fn:function( field,  newValue,  oldValue, eOpts ){
						this.saveField('alias' , newValue);
					},
					scope:this,
					buffer:500
				}
			}
		});
			
		if(!this.valueIsLink){
			this.fieldAddSub = {xtype:'displayfield', width:30};
		}else{
			this.fieldAddSub = Ext.create('Ext.button.Button',{
				text:'Sub',
				width:30,
				disabled:this.valueSelectSub,
				scope:this,
				handler:this.selectSub
			});
		}
		

		this.fieldPanel = Ext.create('Ext.panel.Panel',{
			layout:'column',
			//bodyCls : 'formBody',
			//bodyPadding:3,
			autoHeight:true,
			border:false,
			items:[
		              this.fieldSelected,
		              {xtype:'panel', items:[this.fieldAddSub], width:50,border:false},
		              {xtype:'displayfield', value:'<b>' + this.valueField + '</b>', width:150},
		              {xtype:'displayfield', value:appLang.ALIAS, width:40}, 
		              this.fieldAlias,
		              {xtype:'displayfield',width:20},
		              {xtype:'displayfield',value:appLang.TITLE, width:40},
		              this.fieldTitle			       
			]
		});
		
		
		this.items = [this.fieldPanel];
		
		if(this.valueIsLink){			
			this.childPanel = Ext.create('app.FieldSet' , {
				collapsible:true,
				collapsed:true,
				title:this.valueSubObjectTtile + ' ('+this.valueSubObject+')',
				items:[],
				bodyBorder:false,
				autoHeight:true,
				hidden:!this.valueSelectSub,
				padding:5,
				listeners:{
					'beforeexpand':{
						fn:function(cmp){
							if(!this.itemsLoaded){
								this.loadPart();
							}
						},
						scope:this
					}				
				}
			});			
			this.items.push(this.childPanel);
		}
		
		this.callParent(arguments);		
		this.addEvents(
				/**
	             * @event dataChanged
	             */
				'dataChanged'
		);
	},
	loadPart:function(){
		var me = this;
		me.getEl().mask(appLang.LOADING);
		Ext.Ajax.request({
		 		url: app.root+ "loadpart",
		 		method: 'post',
		 		params:{
		 			object:me.valueSubObject,
		 			parentpart:me.valuePartId,
		 			parentfield:me.valueField
		 		},
		        success: function(response, request) {
		 			response =  Ext.JSON.decode(response.responseText);
		 			if(response.success){
		 				me.childPanel.removeAll(); 
		 				me.childPanel.add({
		 					xtype:'joinselector',
		 					value:response.data.objectcfg.join,
		 					parentPart:me.valuePartId,
		 					object:me.valueSubObject,
		 					parentField:me.valueField,
		 					listeners:{
		 						partRemoved:{
		 							fn:me.partRemoved,
		 							scope:me
		 						}
		 					}
		 				});
		 				me.childPanel.setTitle(response.data.objectcfg.title + ' ('+response.data.objectcfg.object+')');
		 				me.childPanel.add(response.data.items);
		 				me.itemsLoaded = true;
		 			}else{
		 			    Ext.Msg.alert(appLang.MESSAGE,response.msg);   	
		 			}
		 			me.getEl().unmask();
		       },
		       failure:function() {
		       		Ext.Msg.alert(appLang.MESSAGE, appLang.MSG_LOST_CONNECTION);   
		       		me.getEl().unmask();
		       }
		 });
	},
	partRemoved:function()
	{	
		this.childPanel.removeAll();
		this.childPanel.hide();
		this.fieldAddSub.enable();
		this.itemsLoaded = false;
	},
	selectSub: function(){
		var me = this;
		Ext.Ajax.request({
	 		url: app.root+ "addpart",
	 		method: 'post',
	 		params:{
	 			subobject : me.valueSubObject,
	 			partid: me.valuePartId,
	 			objectfield:me.valueField
	 		},
	        success: function(response, request) {
	 			response =  Ext.JSON.decode(response.responseText);
	 			if(response.success){			
	 				if(!Ext.isEmpty(response.limit, false) && response.limit){
	 					me.childPanel.hide();
		 				me.fieldAddSub.enable();
		 				Ext.Msg.alert(appLang.MESSAGE,response.msg); 
	 				}else{	 				
		 				me.childPanel.show();
		 				me.childPanel.expand();
		 				me.fieldAddSub.disable();
	 				}
	 					
	 			}else{
	 			    Ext.Msg.alert(appLang.MESSAGE,response.msg);   	
	 			}
	       },
	       failure:function() {
	       		Ext.Msg.alert(appLang.MESSAGE, appLang.MSG_LOST_CONNECTION);   	
	       }
	 });
	},
	saveField:function(field , value){
		var me = this;
		Ext.Ajax.request({
	 		url: app.root+ "savefield",
	 		method: 'post',
	 		params:{
	 			part : me.valuePartId,
	 			value:value,
	 			field:me.valueField,
	 			fieldoption:field
	 		},
	        success: function(response, request) {
	 			response =  Ext.JSON.decode(response.responseText);
	 			if(response.success){			
	 				me.fireEvent('dataChanged');
	 			}else{
	 			    Ext.Msg.alert(appLang.MESSAGE,response.msg);   	
	 			}
	       },
	       failure:function() {
	       		Ext.Msg.alert(appLang.MESSAGE, appLang.MSG_LOST_CONNECTION);   	
	       }
		});
	}
});


Ext.define('app.crud.reports.ResultPanel',{
	extend:'Ext.Panel',
	dataGrid:null,
	dataStore:null,
	layout:'fit',
	
	initComponent:function(){
		
		this.tbar = [
		    {
		    	icon:'/i/system/designer/csv.png',
		    	tooltip:appLang.EXPORT_TO_CSV,
		    	handler:this.exportCSV,
		    	scope:this
		    }
		];
		
		this.callParent(arguments);
	},
	
	loadResult:function(){
		 var me = this;
		 Ext.Ajax.request({
		 		url: app.root + "results",
		 		method: 'post',
		        success: function(response, request) {
		 			response =  Ext.JSON.decode(response.responseText);
		 			me.removeAll();
		 		
		 			if(!response.success)
		 				return; 		
	
	 				me.dataStore = Ext.create('Ext.data.Store', {
	 				    fields:response.data.fields,
		 				proxy: {
					        type: 'ajax',
					        url: app.root+ 'data',
					        reader: {
					            type: 'json',
					            root: 'data',
					            totalProperty: 'count',
					            idProperty: 'id'
					        },
					        startParam:'pager[start]',
					        limitParam:'pager[limit]',
					        sortParam:'pager[sort]',
					        directionParam:'pager[dir]',
					        extraParams:{
					        },
					        simpleSortMode: true
		 				},
					    pageSize: 200,
				        remoteSort: true,
					    autoLoad: true
	 				});
	 				
	 				me.dataGrid = Ext.create('Ext.grid.Panel',{
						store: me.dataStore,
						viewConfig: {
							stripeRows: true
						},
			            frame: false,
			            loadMask:true,
					    columnLines: true,
					    autoscroll:true,
					    bodyBorder:false,
						border:false,
					    columns: response.data.columns,
					    bbar: Ext.create('Ext.PagingToolbar', {
				            store: me.dataStore,
				            displayInfo: true,
				            displayMsg: appLang.DISPLAYING_RECORDS +' {0} - {1} '+appLang.OF+' {2}',
				            emptyMsg:appLang.NO_RECORDS_TO_DISPLAY
				        })
				    });
	 				me.add(me.dataGrid);
	 				//me.dataGrid.on('columnmove',me.onColMove , me);
		 			
		       },
		       failure:function() {
		       		Ext.Msg.alert(appLang.MESSAGE, appLang.MSG_LOST_CONNECTION);   	
		       }
		 });
	},/*,
	onColeMove:function(ct, column, fromIdx, toIdx, eOpts ){
		var cols = ct.getGridColumns();
		Ext.each(cols,function(item){
			console.log(item);
		},this);
	}
	*/
	exportCSV:function(){
		window.location = app.root+ "exportcsv";
	}
});


Ext.define('app.crud.reports.Main',{
	extend:'Ext.tab.Panel',
	
	controllerUrl:'',
	
	reportQuery:null,
	reportPanel:null,
	reportResult:null,
	reportBuilder:null,
	
	/*
	 * Buttons
	 */
	buttonBase:null,
	buttonSub:null,
	buttonLoad:null,
	buttonSave:null,
	buttonCreate:null,
	buttonSqlReload:null,
	buttonClose:null,
	buttonDeleteBase:null,
	

	initComponent:function(){
		 		 
		this.buttonLoad = Ext.create('Ext.Button',{
			 tooltip:appLang.LOAD_REPORT,
			 icon:'/i/system/designer/open.png',
			 handler:this.selectReport,
			 scope:this
		 });
		
		this.buttonSave= Ext.create('Ext.Button',{
			 tooltip:appLang.SAVE_REPORT,
			 icon:'/i/system/designer/save.png',
			 handler:this.saveReport,
			 scope:this,
			 hidden:true
		});
		
		this.buttonCreate= Ext.create('Ext.Button',{
			 tooltip:appLang.CREATE_REPORT,
			 icon:'/i/system/designer/new.png',
			 handler:this.createReport,
			 scope:this
		});
		
		this.buttonSqlReload= Ext.create('Ext.Button',{
			 icon:'/i/system/designer/refresh.png',
			 tooltip:appLang.RELOAD_SQL,
			 handler:function(){this.loadSql();},
		   	 scope:this,
		   	 hidden:true
		});
		
		this.buttonClose= Ext.create('Ext.Button',{
			 icon:'/i/system/designer/exit.png',
			 tooltip:appLang.CLOSE,
			 handler:this.closeReport,
			 scope:this,
			 hidden:true
		});

		this.tbar = [this.buttonLoad ,this.buttonSave];
		 
		 if(app.crud.reports.canEdit){
			 this.tbar.push(this.buttonCreate);
		 }
		 
		 this.tbar.push([this.buttonSqlReload,this.buttonClose]);
		 
		 this.activeTab = 0;

		 this.reportResult = Ext.create('app.crud.reports.ResultPanel',{
			 title:appLang.QUERY_RESULT
		 });
		 
		 this.reportResult.on('activate',function(){
			 this.reportResult.loadResult();
		 },this);
		 		 
		 this.reportQuery = Ext.create('Ext.panel.Panel',{
			region:'north',
			height:150,
			split:true,
			bodyPadding:10
		 });

		 
		 this.buttonBase = Ext.create('Ext.Button',{
			 text:appLang.BASE_OBJECT,
			 handler:this.addBaseObj,
			 hidden:true,
			 scope:this
		 });
		 
		 this.buttonSub = Ext.create('Ext.Button',{
			 text:appLang.SUB_OBJECT,
			 hidden:true,
			 handler:this.addSubObject,
			 scope:this
		 });
		 
		 this.buttonDeleteBase = Ext.create('Ext.Button',{
			 tooltip:appLang.CLEAR,
			 hidden:true,
			 handler:this.clearReport,
			 scope:this,
			 icon:'/i/system/delete.gif'
		 });
		 
		 
		 this.reportBuilder = Ext.create('Ext.form.Panel',{
			 region:'center',
			 split:true,
			 bodyPadding:3,
			 //bodyCls :'formBody',
			 autoScroll:true,
			 border:true,
			 tbar:[
			      this.buttonDeleteBase,
		          this.buttonBase,
		          '-',
		          this.buttonSub
			 ]
		 });
		 
		 this.filterPanel = Ext.create('app.report.filter.Main',{
			 region:'east',
			 controllerUrl:app.root,
			 minWidth:250,
			 width:400,
			 split:true,
			 canEdit:app.crud.reports.canEdit,
			 canDelete:app.crud.reports.canDelete
		 });
		 	 	 
		 this.reportPanel = Ext.create('Ext.panel.Panel',{
			 title:appLang.QUERY_BUILDER,
			 layout:'border',
			 split:true,
			 items:[this.reportQuery , this.reportBuilder , this.filterPanel]
		 });
		 
		 this.items = [this.reportPanel , this.reportResult] ;
		 
		 this.callParent(arguments);
	 },
	 /**
	  * Reset interface layout
	  */
	 resetInterface:function(){	 
		this.buttonBase.hide();
		this.buttonSub.hide();
		this.buttonCreate.show();
		this.buttonLoad.show();
		this.buttonSave.hide();
		this.buttonSqlReload.hide();
		this.buttonClose.hide();
		this.buttonDeleteBase.hide();
		this.reportBuilder.removeAll();
		this.reportQuery.removeAll();
		this.reportBuilder.setTitle('');
	 },
	 /**
	  * Check if report is loaded
	  */
	 checkIsLoaded: function(){

		 Ext.Ajax.request({
		 		url: app.root+ "checkloaded",
		 		method: 'post',
		 		scope:this,
		        success: function(response, request) {
		 			response =  Ext.JSON.decode(response.responseText);
		 			
		 			if(!response.success){
		 				return;
		 			}
		 			
		 			this.reportBuilder.removeAll();
	 				
	 				if(!Ext.isEmpty(response.data.items)){
	 					this.reportBuilder.add(response.data.items);
	 					this.buttonBase.hide();
	 					this.buttonSub.show();
	 					this.buttonDeleteBase.show();
	 					this.loadSql();
	 				}else{
	 					this.buttonBase.show();
	 					this.buttonSub.hide();
	 					this.buttonDeleteBase.hide();
	 				}	 	
	 				
	 				this.buttonCreate.hide();
	 				this.buttonLoad.hide();
	 				this.buttonSave.show();
	 				this.buttonSqlReload.show();
	 				this.buttonClose.show();
		 			this.reportBuilder.setTitle(response.data.partconfig.title + ' ('+response.data.partconfig.object+')');
		 			
		       },
		       failure:function() {
		       		Ext.Msg.alert(appLang.MESSAGE, appLang.MSG_LOST_CONNECTION);   	
		       }
		 });
	 },
	 loadSql:function(){
		 var me = this;
		 Ext.Ajax.request({
		 		url: app.root+ "loadsql",
		 		method: 'post',
		        success: function(response, request) {
		 			response =  Ext.JSON.decode(response.responseText);
		 			if(response.success){
		 				me.reportQuery.removeAll();
		 				me.reportQuery.add({xtype:'displayfield',value:response.data});
		 					
		 			}else{
		 				return; 
		 			}
		       },
		       failure:function() {
		       		Ext.Msg.alert(appLang.MESSAGE, appLang.MSG_LOST_CONNECTION);   	
		       }
		 });
	 },
	 selectReport:function(){
		 var win = Ext.create('app.FilesystemWindow',{
			 title:appLang.SELECT_REPORT,
			 controllerUrl:this.controllerUrl,
			 listeners:{
				 fileSelected:{
					 fn:this.loadReport,
					 scope:this
				 }
			 }
		 }).show();

	 },
	 createReport:function(){
		 var win = Ext.create('app.FilesystemWindow',{
			 title:appLang.SELECT_REPORT,
			 controllerUrl:this.controllerUrl,
			 viewMode:'create',
			 createExtension:'.report.dat',
			 listeners:{
				 fileCreated:{
					 fn:this.loadReport,
					 scope:this
				 }
			 }
		 }).show();
	 },
	 /**
	  * Close report
	  */
	 closeReport:function(){
		 var me = this;
		 Ext.Msg.confirm(appLang.CONFIRMATION, appLang.MSG_SAVE_BEFORE_CLOSE, function(btn){
			 
			 if(btn == 'yes'){
				 var handle = function(){
					me.resetInterface();
					me.clearSession();
				 };
				 me.saveReport(handle);
			 }else{
				 me.clearSession();
				 me.resetInterface();
			 }
			   
		 }, this);
	 },
	 /**
	  * Clear report
	  */
	 clearReport:function(){
		 var me = this;
		 Ext.Ajax.request({
		 	url: app.root+ "clear",
		 	method: 'post',
		    success: function(response, request) {
		 		response =  Ext.JSON.decode(response.responseText);
		 		if(response.success){
		 			me.resetInterface();
		 			me.checkIsLoaded();
		 		}else{
		 		    Ext.Msg.alert(appLang.MESSAGE,response.msg);   	
		 		}
		    },
		    failure:function() {
		       	Ext.Msg.alert(appLang.MESSAGE, appLang.MSG_LOST_CONNECTION);   
		    }
		 });
	 },
	 /**
	  * Load report
	  * @param string name - report ID
	  */
	 loadReport:function(name){
			var me = this;
			me.getEl().mask(appLang.LOADING);
			Ext.Ajax.request({
			 	url: app.root+ "load",
			 	method: 'post',
			 	params:{
			 			file:name
			 	},
			    success: function(response, request) {
			 		response =  Ext.JSON.decode(response.responseText);
			 		if(response.success){
			 			me.checkIsLoaded();
			 		}else{
			 		    Ext.Msg.alert(appLang.MESSAGE,response.msg);   	
			 		}
			 		me.getEl().unmask();
			    },
			    failure:function() {
			       	Ext.Msg.alert(appLang.MESSAGE, appLang.MSG_LOST_CONNECTION);   
			       	me.getEl().unmask();
			    }
			 });
	 },	 
	 /**
	  * Save report
	  * @param function callback
	  */
	 saveReport:function(callback){
		 
		 	var me = this;
			me.getEl().mask(appLang.SAVING);
			Ext.Ajax.request({
			 		url: app.root+ "save",
			 		method: 'post',
			        success: function(response, request) {
			 			response =  Ext.JSON.decode(response.responseText);
			 			if(!response.success){
			 			    Ext.Msg.alert(appLang.MESSAGE,response.msg);   	
			 			}
			 			me.getEl().unmask();
			 			if(typeof callback == 'function'){
			 				callback();
			 			}
			       },
			       failure:function() {
			       		Ext.Msg.alert(appLang.MESSAGE, appLang.MSG_LOST_CONNECTION);   
			       		me.getEl().unmask();
			       }
			 });
	 },
	 /**
	  * Clear report session
	  */
	 clearSession:function(){
		 Ext.Ajax.request({
		 		url: app.root+ "close",
		 		method: 'post',
		        success: function(response, request) {
		 			
		       },
		       failure:function() {
		       		Ext.Msg.alert(appLang.MESSAGE, appLang.MSG_LOST_CONNECTION);   
		       }
		 });
	 },
	 /**
	  * Add base object for report
	  */
	 addBaseObj:function(){
		 var win = Ext.create('app.crud.reports.addMainWindow',{
			 listeners:{
				 objectAdded:{
					 fn:this.checkIsLoaded,
					 scope:this
				 }
			 }
		 }).show();
	 },
	 /**
	  * Add sub object selection
	  */
	 addSubObject:function(){
		 var win = Ext.create('app.crud.reports.addSubWindow',{
			 listeners:{
				 objectAdded:{
					 fn:this.checkIsLoaded,
					 scope:this
				 }
			 }
		 }).show();
	 }
	 
});


Ext.define('app.crud.reports.addMainWindow',{
	extend:'Ext.Window',
	width:300,
	height:100,
	dataForm:null,
	closeAction:'desyroy',
	title:appLang.BASE_OBJECT,
	layout:'fit',
	resizable:false,
	modal:true,
	initComponent:function(){
		this.dataForm = Ext.create('Ext.form.Panel',{
			bodyPadding:3,
			bodyCls:'formBody',
			border:false,
			fieldDefaults:{
				labelWidth:60,
				anchor:'100%'
			},
			items:[
				Ext.create('Ext.form.field.ComboBox',{
					  displayField:'title',
					  valueField:'id',
					  queryMode:'local',
					  value:'',
					  allowBlank:false,
					  forceSelection:true,
					  fieldLabel:appLang.OBJECT,
					  name:'object',
					  store:Ext.create('Ext.data.Store', {
						  model:'app.comboStringModel',
						  proxy: {
						        type: 'ajax',
						        url: app.root + 'objects',
						        reader: {
						            type: 'json',
						            root: 'data',
						            idProperty: 'id'
						        },
						        simpleSortMode: true
			 				},
			 			 autoLoad:true	
					  })
					})
			]
		});
		this.items = [this.dataForm];
		this.buttons = [
		  {
			  text:appLang.ADD,
			  scope:this,
			  handler:this.formSubmit
		  },{
			  text:appLang.CANCEL,
			  scope:this,
			  handler:this.close
		  }            
		];
		this.callParent(arguments);
		
		
		this.addEvents(
				/**
	             * @event objectAdded
	             */
				'objectAdded'
		);  
	},
	formSubmit:function(){
		var me = this;
		this.dataForm.getForm().submit({
			clientValidation: true,
			waitTitle:appLang.SAVING,
			method:'post',
			url:app.root +  'addbase',
			success: function(form, action) 
			{	
   		 		if(!action.result.success){
   		 			Ext.Msg.alert(appLang.MESSAGE, action.result.msg);
   		 			return;
   		 		} 
   		 		me.fireEvent('objectAdded');
   		 		me.close();
   	        },
   	        failure: app.formFailure
		});
	}
});

Ext.define('app.crud.reports.addSubWindow',{
	extend:'Ext.Window',
	width:350,
	height:200,
	dataForm:null,
	closeAction:'desyroy',
	title:appLang.SUB_OBJECT,
	layout:'fit',
	resizable:false,
	modal:true,
	objectName:0,
	
	
	fieldListConfig: {
		  getInnerTpl: function() {
		      return '<tpl for="."><b>{id}</b> - {title}</tpl>';
		  }
    },
	
	initComponent:function(){

		
		
		this.dataForm = Ext.create('Ext.form.Panel',{
			bodyPadding:3,
			bodyCls:'formBody',
			border:false,
			fieldDefaults:{
				labelWidth:100,
				anchor:'100%'
			},
			items:[
			   {
				  xtype:'combo',
				  displayField:'title',
				  valueField:'id',
				  queryMode:'local',
				  value:'',
				  allowBlank:false,
				  forceSelection:true,
				  fieldLabel:appLang.PARENT_FIELD,
				  name:'basefield',
				  listConfig: this.fieldListConfig,
				  store:Ext.create('Ext.data.Store', {
					  model:'app.comboStringModel',
					  sorters:[{
				             property : 'title',
				             direction: 'ASC'
				      }],
					  proxy: {
					        type: 'ajax',
					        url: app.root + 'objectfields',
					        reader: {
					            type: 'json',
					            root: 'data',
					            idProperty: 'id'
					        },
					        extraParams :{
					        	object:this.objectName
					        },
					        simpleSortMode: true
						},
					 autoLoad:true
				  })
				},{
				   	  xtype:'combo',
					  displayField:'title',
					  valueField:'id',
					  queryMode:'local',
					  value:'',
					  allowBlank:false,
					  forceSelection:true,
					  fieldLabel:appLang.RELATED_OBJECT,
					  name:'subobject',
					  store:Ext.create('Ext.data.Store', {
						  model:'app.comboStringModel',
						  sorters:[{
					             property : 'title',
					             direction: 'ASC'
					       }],
						  proxy: {
						        type: 'ajax',
						        url: app.root + 'objects',
						        reader: {
						            type: 'json',
						            root: 'data',
						            idProperty: 'id'
						        },
						        simpleSortMode: true
			 				},
			 			 autoLoad:true	
					  }),
					  listeners:{
						  select:{
							  fn:function(cmp){
								  var subField =  this.dataForm.getForm().findField('subfield');
								  subField.getStore().proxy.extraParams['object'] = cmp.getValue();
								  subField.getStore().load();
							  },
							  scope:this
						  }
					  }
					},{
						  xtype:'combo',
						  displayField:'title',
						  valueField:'id',
						  queryMode:'local',
						  value:'',
						  allowBlank:false,
						  forceSelection:true,
						  fieldLabel:appLang.LINK_FIELD,
						  name:'subfield',
						  listConfig: this.fieldListConfig,
						  store:Ext.create('Ext.data.Store', {
							  model:'app.comboStringModel',
							  sorters:[{
						             property : 'title',
						             direction: 'ASC'
						      }],
							  proxy: {
							        type: 'ajax',
							        url: app.root + 'objectfields',
							        reader: {
							            type: 'json',
							            root: 'data',
							            idProperty: 'id'
							        },
							        extraParams :{
							        	object:this.objectName
							        },
							        simpleSortMode: true
							  },
							  autoLoad:false	
						  })
					 },{
						  xtype:'combo',
				      	  displayField:'title',
				      	  valueField:'id',
				      	  queryMode:'local',
				      	  value:1,
				      	  forceSelection:true,
				      	  name:'join',
				      	  fieldLabel:appLang.JOIN_TYPE,
				      	  store:Ext.create('Ext.data.Store', {
				      		  model:'app.comboModel',
				      		  data:[
				      		        {id:1, title:"Left"},
				      		        {id:2 ,title:"Right"},
				      		        {id:3 ,title:"Inner"}
				      		  ]
				      	  })
					}
			]
		});
		this.items = [this.dataForm];
		this.buttons = [
		  {
			  text:appLang.ADD,
			  scope:this,
			  handler:this.formSubmit
		  },{
			  text:appLang.CANCEL,
			  scope:this,
			  handler:this.close
		  }            
		];
		this.callParent(arguments);
		
		this.addEvents(
				/**
	             * @event objectAdded
	             */
				'objectAdded'
		);  
	},
	formSubmit:function(){
		var me = this;
		this.dataForm.getForm().submit({
			clientValidation: true,
			waitTitle:appLang.SAVING,
			method:'post',
			url:app.root +  'addSub',
			success: function(form, action) 
			{	
   		 		if(!action.result.success){
   		 			Ext.Msg.alert(appLang.MESSAGE, action.result.msg);
   		 			return;
   		 		} 
   		 		me.fireEvent('objectAdded');
   		 		me.close();
   	        },
   	        failure: app.formFailure
		});
	}
});

Ext.onReady(function(){ 
	Ext.QuickTips.init();
	
	app.crud.reports.canEdit = canEdit;
	app.crud.reports.canDelete = canDelete;	
	
	var appMain = Ext.create('app.crud.reports.Main',{title:'Reports :: Home',controllerUrl:app.root});
			
	app.content.add(appMain);	
	appMain.checkIsLoaded();
});
	

